import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import StandardTable from '@/components/StandardTable';
import { allDictList } from '@/utils/constans';
import { renderTableAdSelect, codes, caclTotal, getBillOilDetails } from './utils';
import styles from '@/pages/Info.less';

@connect(({ vehicle, component, loading }) => ({
  vehicle,
  billDetail: vehicle.billDetail,
  oilInfoList: vehicle.oilInfoList,
  dictObject: component.dictObject,
  loading: loading.effects['vehicle/seleceBillOilInfo'],
}))
export default class BillOilInfo extends Component {
  state = {
    infoList: [],
    id: '',
  };

  componentDidMount() {
    const { dispatch, billDetail, detailId, open } = this.props;
    const details = billDetail[detailId] || {};
    const id = open ? details.id : detailId;
    this.setState({
      id,
    });
    getBillOilDetails(dispatch, id, open);
  }

  componentWillReceiveProps(nextProps, nextState) {
    const { detailId, billDetail, open } = nextProps;
    if (
      JSON.stringify(billDetail) !== JSON.stringify(this.props.billDetail) ||
      this.props.detailId !== detailId
    ) {
      const detail = billDetail[detailId];
      if (detailId && detail) {
        this.setState({
          id: detail.id,
        });
        getBillOilDetails(this.props.dispatch, detail.id, open);
      }
    }
  }

  oilColumns = list => {
    const data = list ? list.list : [];
    return [
      {
        title: '单价',
        dataIndex: 'price',
        render: (text, record, index) => {
          if (data.length > 0 && data.length - 1 === index) {
            return <span>{text}</span>;
          } else {
            return <span>{text && text !== 0 ? Number(text).toFixed(2) : 0}</span>;
          }
        },
      },
      {
        title: '币种',
        dataIndex: 'currencyType',
        render: text =>
          renderTableAdSelect({
            props: this.props,
            value: text,
            key: allDictList.currencyType,
          }),
      },
      {
        title: '加油量（L）',
        dataIndex: 'oilAmount',
        render: text => <span>{text && text !== 0 ? Number(text).toFixed(2) : 0}</span>,
      },

      {
        title: '总金额',
        dataIndex: 'totalFee',
        render: text => <span>{text && text !== 0 ? Number(text).toFixed(2) : 0}</span>,
      },
    ];
  };

  render() {
    const { loading, oilInfoList, detailId } = this.props;
    const { id } = this.state;

    return (
      <Fragment>
        <StandardTable
          disabledRowSelected={true}
          loading={loading}
          data={oilInfoList[id] || {}}
          columns={this.oilColumns(oilInfoList[id])}
          scrollX={450}
          pagination={false}
          scrollY={200}
          className="table_info_total"
        />
      </Fragment>
    );
  }
}
